package com.xiaoma.juc.countdownlatch;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author xiaomacdut
 * @date 2020年2月11日 上午11:51:11
 */
/**
 * @Author: 王琦 <QQ.Eamil>1124602935@qq.com</QQ.Eamil>
 * @Date: 2019-5-4 0004 9:43
 * @Description: 倒计时器示例:火箭发射
 */
public class CountDownLatchDemo{
    
    static final CountDownLatch countDownlatch = new CountDownLatch(10);
    
    
    public static void main(String [] args) throws InterruptedException{
        ExecutorService exec = Executors.newFixedThreadPool(10);


        for(int i = 0; i < 10; i++){
            exec.submit(new CheckTask());
        }
        
        // 等待检查
        countDownlatch.await();

/*        new Thread(() -> {

            System.out.println("sssss");
            try {
                countDownlatch.await();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }).start();*/
        
        // 发射火箭
        System.out.println("Fire!");
        // 关闭线程池
        exec.shutdown();
    }
    
    static class CheckTask implements Runnable{
        @Override
        public void run(){
            // 模拟检查任务
            try{
                Thread.sleep(new Random().nextInt(10) * 1000);
                System.out.println("check complete"+Thread.currentThread().getName());
            }catch(InterruptedException e){
                e.printStackTrace();
            }finally{
                // 计数减一
                // 放在finally避免任务执行过程出现异常，导致countDown()不能被执行
                countDownlatch.countDown();
            }
        }
    }
}
